<?php

namespace App\Http\Controllers;

use App\Models\UserAddress;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Inertia\Response;

class UserAddressController extends Controller
{
    /**
     * 显示地址列表
     */
    public function index(): Response
    {
        $addresses = Auth::user()->addresses()->orderBy('is_default', 'desc')->orderBy('created_at', 'desc')->get();
        
        return Inertia::render('Profile/Addresses', [
            'addresses' => $addresses
        ]);
    }

    /**
     * 创建新地址
     */
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'province' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:255',
            'district' => 'nullable|string|max:255',
            'address' => 'required|string',
            'postal_code' => 'nullable|string|max:10',
            'label' => 'nullable|string|max:50',
            'is_default' => 'boolean',
        ]);

        $address = Auth::user()->addresses()->create($validated);

        // 如果设置为默认地址
        if ($request->is_default) {
            $address->setAsDefault();
        }

        return redirect()->back();
    }

    /**
     * 更新地址
     */
    public function update(Request $request, UserAddress $address): RedirectResponse
    {
        // 确保只能编辑自己的地址
        if ($address->user_id !== Auth::id()) {
            abort(403);
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'province' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:255',
            'district' => 'nullable|string|max:255',
            'address' => 'required|string',
            'postal_code' => 'nullable|string|max:10',
            'label' => 'nullable|string|max:50',
            'is_default' => 'boolean',
        ]);

        $address->update($validated);

        // 如果设置为默认地址
        if ($request->is_default) {
            $address->setAsDefault();
        }

        return redirect()->back();
    }

    /**
     * 删除地址
     */
    public function destroy(UserAddress $address): RedirectResponse
    {
        // 确保只能删除自己的地址
        if ($address->user_id !== Auth::id()) {
            abort(403);
        }

        $address->delete();

        return redirect()->back();
    }

    /**
     * 设置默认地址
     */
    public function setDefault(UserAddress $address): RedirectResponse
    {
        // 确保只能设置自己的地址
        if ($address->user_id !== Auth::id()) {
            abort(403);
        }

        $address->setAsDefault();

        return redirect()->back();
    }
}
